package com.zqxq.lottery.service.user.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zqxq.common.constant.Result;
import com.zqxq.common.enums.CodeEnum;
import com.zqxq.common.utils.StrUtils;
import com.zqxq.lottery.common.constant.HuaYangConstant;
import com.zqxq.lottery.entity.bo.sys.SysActivityBO;
import com.zqxq.lottery.entity.enums.ActivityIdEnum;
import com.zqxq.lottery.entity.po.esports.ESportsPO;
import com.zqxq.lottery.entity.po.sys.SysConfigPO;
import com.zqxq.lottery.entity.po.sys.SysCouponPO;
import com.zqxq.lottery.entity.po.user.*;
import com.zqxq.lottery.entity.vo.order.UserOrderVO;
import com.zqxq.lottery.mapper.esports.ESportsMapper;
import com.zqxq.lottery.mapper.sys.SysConfigMapper;
import com.zqxq.lottery.mapper.sys.SysCouponMapper;
import com.zqxq.lottery.mapper.user.*;
import com.zqxq.lottery.config.YmlConfig;
import com.zqxq.lottery.entity.po.order.UserOrderPO;
import com.zqxq.lottery.mapper.order.UserOrderMapper;
import com.zqxq.lottery.service.order.IUserOrderService;
import com.zqxq.lottery.service.sys.ISysActivityService;
import com.zqxq.lottery.service.user.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
@Slf4j
public class UserFundsServiceImpl extends ServiceImpl<UserFundsMapper, UserFundsPO> implements IUserFundsService {

    private String msg_rechange = "您在%s成功充值%s元，余额为%s。";
    private String msg_deposit = "您好，您申请的 %s 元已付款成功，请前往支付宝查看";

    @Autowired
    private UserCashMapper userCashMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserFundsMapper userFundsMapper;

    @Autowired
    private UserOrderMapper userOrderMapper;

    @Autowired
    private IUserMsgService userMsgService;

    @Autowired
    private YmlConfig ymlConfig;

    @Autowired
    private ISysActivityService sysActivityService;

    @Autowired
    private IUserOrderService userOrderService;

    @Autowired
    private UserCouponMapper userCouponMapper;

    @Autowired
    private SysCouponMapper sysCouponMapper;

    @Autowired
    private UserInviteMapper userInviteMapper;

    @Autowired
    private IUserCashService userCashService;

    @Autowired
    private UserAgentMapper userAgentMapper;

    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IUserWindowMsgService userWindowMsgService;
    @Autowired
    private ESportsMapper eSportsMapper;

    /**
     * 充值消费
     *
     * @param userId
     * @param money
     * @param type       1-充值；2-提现；3-奖金；4-竞猜
     * @param payWay     支付方式 0-系统；1-支付宝；2-银行卡；3-奖金；4-余额；5-红包；6-微信；99-其它
     * @param payAccount
     */
    @Transactional
    @Override
    public boolean saveRechargeOrConsume(Long userId, BigDecimal money, Integer type, Integer payWay, String payAccount, Long cashId) {
        boolean result = false;
        UserInfoPO userInfoPO = userInfoMapper.selectById(userId);
        UserFundsPO userFundsPO = userFundsMapper.selectById(userId);
        if (userInfoPO == null || userFundsPO == null) {
            return result;
        }

        UserCashPO userCashPO = new UserCashPO();
        if (cashId == null) {
            cashId = ymlConfig.getPkId();
        }
        userCashPO.setId(cashId);
        userCashPO.setUser_id(userId);
        userCashPO.setReal_name(userInfoPO.getReal_name());
        userCashPO.setMobile(userInfoPO.getMobile());
        userCashPO.setPay_way(payWay);
        userCashPO.setPay_account(payAccount);
        userCashPO.setPay_amount(money);

        userCashPO.setType(type);
        Integer status = 4;
        BigDecimal remainder = new BigDecimal(0.00);
        //充值
        if (type.equals(1)) {
            remainder = userFundsPO.getBonus().add(money).setScale(2, 4);
            BigDecimal total = userFundsPO.getBonus().add(userFundsPO.getBalance()).add(userFundsPO.getLot_bean()).add(money).setScale(2, 4);
            DateFormat df = DateFormat.getTimeInstance();//只显示出时分秒
            userMsgService.saveUserMsg(userId,String.format(msg_rechange,df.format(new Date()),money,total),1);
            //充值奖励活动
            /*SysConfigPO sysConfigPO = sysConfigMapper.getByKey("RECHARGE_GIFT_RATIO");
            if(sysConfigPO!=null){
                Map map = JSONObject.parseObject(sysConfigPO.getCval(), Map.class);
                Integer a = money.divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP).intValue();
                BigDecimal retio = new BigDecimal((String) map.get(String.valueOf(a)));
                if(retio.compareTo(BigDecimal.ZERO)>0){
                    savegiftRatio(userInfoPO,money.multiply(retio.divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP)));
                }
            }*/

        } else if (type.equals(2)) {
            if(money.compareTo(userFundsPO.getBalance())>0)
                return false;
            remainder = userFundsPO.getBalance().subtract(money).setScale(2, 4);
            if (remainder.doubleValue() < 0) {
                return result;
            }
            userMsgService.saveUserMsg(userId,String.format(msg_deposit,money),2);
            status = 1;
        } else if (type.equals(3)) {
            remainder = userFundsPO.getBalance().add(money).setScale(2, 4);
        } else if (type.equals(4)) {
            remainder = userFundsPO.getBalance().subtract(money).setScale(2, 4);
            if (remainder.doubleValue() < 0) {
                return result;
            }
        } else {
            return result;
        }
        userCashPO.setRemainder(remainder);
        userCashPO.setStatus(status);
        this.baseMapper.updateUserBonus(userId, remainder);
        Integer flag = userCashMapper.insert(userCashPO);
        if(flag>0) {
            /*try {
                SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
                Long createTime = userInfoPO.getCreate_time().getTime();
                Calendar c = Calendar.getInstance();
                c.setTime(new Date());
                c.add(Calendar.DAY_OF_MONTH, -90);
                Date Days90Ago = c.getTime();
                String dateStr = f.format(Days90Ago);
                Date date = f.parse(dateStr);
                Long Days90AgoTime = date.getTime();
                //注册之日起90天内才享受此奖励
                if(createTime>=Days90AgoTime){
                    //被邀请人首次充值，邀请人奖励x趣豆
                    Wrapper wrapper = new EntityWrapper();
                    wrapper.eq("user_id", userId);
                    wrapper.in("type", "1");
                    Integer count = userCashMapper.selectCount(wrapper);
                    List<UserCashPO> userCashPOList = userCashMapper.selectList(wrapper);
                    BigDecimal totalRecharge = BigDecimal.ZERO;
                    for(UserCashPO userCashPO1 : userCashPOList){
                        totalRecharge = totalRecharge.add(userCashPO1.getPay_amount());
                    }
                    Wrapper wrapper1 = new EntityWrapper();
                    wrapper1.eq("order_id", userId);
                    wrapper1.eq("type",7);
                    wrapper1.eq("info","邀请用户首次下单奖励");
                    Integer count1 = userCashMapper.selectCount(wrapper1);//根据userid查询invitorid
                    UserInviteRecordPO inviteRecordPO = new UserInviteRecordPO();
                    inviteRecordPO.setUser_id(userId);
                    UserInviteRecordPO invitePO = userInviteMapper.selectOne(inviteRecordPO);
                    *//*Wrapper inviterWrapper = new EntityWrapper();
                    inviterWrapper.eq("user_id",invitePO.getInviter_id());
                    inviterWrapper.eq("type","1");
                    Integer inviterCount =  userCashMapper.selectCount(inviterWrapper);
                    List<UserCashPO> inviterUserCashPOList = userCashMapper.selectList(inviterWrapper);
                    BigDecimal inviterTotalRecharge = BigDecimal.ZERO;
                    for(UserCashPO inviterUserCashPO : inviterUserCashPOList){
                        inviterTotalRecharge = inviterTotalRecharge.add(inviterUserCashPO.getPay_amount());
                    }
                    Date inviteDate = invitePO.getCreate_time();
                    Date date1 = f.parse("2018-11-16 00:00:00");*//*
                    if (count == 1) {
                        //首冲奖励
                        Wrapper firstRechargeWrapper = new EntityWrapper();
                        firstRechargeWrapper.eq("user_id", userId);
                        firstRechargeWrapper.eq("type", "7");
                        firstRechargeWrapper.eq("info", "用户首次充值奖励");
                        Integer firstRechargeCount = userCashMapper.selectCount(firstRechargeWrapper);
                        if(firstRechargeCount==0){
                            SysActivityBO sysActivityBO = new SysActivityBO();
                            sysActivityBO.setActivityId(ActivityIdEnum.FIRST_RECHARGE_REWARD.getId());
                            sysActivityBO.setUserId(userId);
                            sysActivityService.saveUserActivity(sysActivityBO);
                        }

                        if (invitePO != null && count1==0){
                            SysActivityBO sysActivityBO = new SysActivityBO();
                            sysActivityBO.setUserId(userId);
                            sysActivityBO.setInviterId(String.valueOf(invitePO.getInviter_id()));
                            sysActivityBO.setActivityId(ActivityIdEnum.RECHARGE_ORDER.getId());
                            sysActivityBO.setConditionMoney(money);
                            sysActivityService.saveUserActivity(sysActivityBO);
                        }
                    }
                    Wrapper wrapper2 = new EntityWrapper();
                    wrapper2.eq("order_id", userId);
                    wrapper2.eq("type",7);
                    wrapper2.eq("info","邀请用户累积充值500奖励");
                    Integer count2 = userCashMapper.selectCount(wrapper2);
                    if(count2==0 && totalRecharge.compareTo(new BigDecimal(50000))>=0){
                        //累积充值500奖励
                        if (invitePO != null){
                            SysActivityBO sysActivityBO = new SysActivityBO();
                            sysActivityBO.setUserId(userId);
                            sysActivityBO.setInviterId(String.valueOf(invitePO.getInviter_id()));
                            sysActivityBO.setActivityId(ActivityIdEnum.RECHARGE_500_ORDER.getId());
                            sysActivityService.saveUserActivity(sysActivityBO);
                        }
                    }
                    Wrapper wrapper3 = new EntityWrapper();
                    wrapper3.eq("order_id", userId);
                    wrapper3.eq("type",7);
                    wrapper3.eq("info","邀请用户累积充值1000奖励");
                    Integer count3 = userCashMapper.selectCount(wrapper3);
                    if(count3==0 && totalRecharge.compareTo(new BigDecimal(100000))>=0){
                        //累积充值1000奖励
                        if (invitePO != null){
                            SysActivityBO sysActivityBO = new SysActivityBO();
                            sysActivityBO.setUserId(userId);
                            sysActivityBO.setInviterId(String.valueOf(invitePO.getInviter_id()));
                            sysActivityBO.setActivityId(ActivityIdEnum.RECHARGE_1000_ORDER.getId());
                            sysActivityService.saveUserActivity(sysActivityBO);
                        }
                    }
                    //充值返0.5%给邀请人
                    *//*if(invitePO != null && inviterCount!=0 && inviteDate.compareTo(date1)>=0 && inviterTotalRecharge.compareTo(new BigDecimal(10000))>=0){
                        saveUserCash(money.multiply(new BigDecimal("0.005")), userInfoMapper.selectById(invitePO.getInviter_id()), 7, "邀请好友返充值额的0.5%奖励",invitePO.getInviter_id());
                    }*//*

                }

            }catch (Exception e){

            }*/

        }
        return true;
    }
    /*private void saveUserCash(BigDecimal money, UserInfoPO userInfoPO,Integer payWay,String info,Long orderId) {
        UserFundsPO fundsPO = userFundsMapper.selectById(userInfoPO.getId());
        boolean f = false;
        if(null == fundsPO){
            fundsPO = new UserFundsPO();
            fundsPO.setUser_id(userInfoPO.getId());
            fundsPO.setLot_bean(BigDecimal.ZERO);
            f = true;
        }
        fundsPO.setLot_bean(fundsPO.getLot_bean().add(money));

        UserCashPO userCashPO = new UserCashPO();
        userCashPO.setId(ymlConfig.getPkId());
        userCashPO.setUser_id(userInfoPO.getId());
        userCashPO.setReal_name(userInfoPO.getReal_name());
        userCashPO.setMobile(userInfoPO.getMobile());
        userCashPO.setPay_way(payWay);
        userCashPO.setPay_account("ZQXQ");
        userCashPO.setType(7);
        userCashPO.setStatus(4);
        userCashPO.setPay_amount(money);
        userCashPO.setInfo(info);
        userCashPO.setOrder_id(orderId);
        userCashService.insert(userCashPO);
        fundsPO.setBonus_status(1);

        if(f){
            userFundsMapper.insert(fundsPO);
        }
        else{
            fundsPO.setCreate_time(null);
            fundsPO.setUpdate_time(null);
            userFundsMapper.updateById(fundsPO);
        }
        userWindowMsgService.saveUserMsg(userInfoPO.getId(),"邀请成功",String.valueOf(money.intValue()),3);
    }*/

    public synchronized void savegiftRatio(UserInfoPO userInfoPO, BigDecimal money) {
        UserFundsPO funds = baseMapper.selectForUpdate(userInfoPO.getId());
        BigDecimal remainder = funds.getLot_bean().add(money).setScale(2, 4);
        UserCashPO userCashPO = new UserCashPO();
        userCashPO.setId(ymlConfig.getPkId());
        userCashPO.setUser_id(userInfoPO.getId());
        userCashPO.setReal_name(userInfoPO.getReal_name());
        userCashPO.setMobile(userInfoPO.getMobile());
        userCashPO.setPay_way(5);
        userCashPO.setPay_amount(money);
        userCashPO.setType(7);
        userCashPO.setRemainder(remainder);
        userCashPO.setStatus(4);
        this.baseMapper.updateUserLotBean(userInfoPO.getId(), remainder);
        userCashMapper.insert(userCashPO);
    }

    @Transactional
    @Override
    public synchronized boolean saveDrawCash(UserInfoPO userInfoPO, BigDecimal money,Integer payWay,String payAccount, Long cashId) {
        boolean result = false;
        UserFundsPO funds = baseMapper.selectForUpdate(userInfoPO.getId());
        int count = userCashService.getDrawCashCount(userInfoPO.getId());
        if(count>=3)
            return false;
        BigDecimal remainder = funds.getBalance().subtract(money).setScale(2, 4);
        if (remainder.doubleValue() < 0) {
            return result;
        }
        UserCashPO userCashPO = new UserCashPO();
        userCashPO.setId(cashId);
        userCashPO.setUser_id(userInfoPO.getId());
        userCashPO.setReal_name(userInfoPO.getReal_name());
        userCashPO.setMobile(userInfoPO.getMobile());
        userCashPO.setPay_way(payWay);
        userCashPO.setPay_account(payAccount);
        userCashPO.setPay_amount(money);
        userCashPO.setType(2);
        Integer status = 4;
        userCashPO.setRemainder(remainder);
        userCashPO.setStatus(status);
        this.baseMapper.updateUserBalance(userInfoPO.getId(), remainder);
        userCashMapper.insert(userCashPO);
        return true;
    }

    /**
     * 说    明：   奖励金消费
     * 创 建 人：	一刀·胡
     * 创建时间：	2018/4/4 13:49
     * 修 改 人：
     * 修改日期：
     **/
    private BigDecimal saveBonuseConsume(UserInfoPO userInfo, BigDecimal money, Long orderId){
        UserFundsPO userFundsPO = userFundsMapper.selectById(userInfo.getId());
        if (null != userFundsPO && userFundsPO.getBonus().intValue()>0&&money.compareTo(userFundsPO.getBalance().add(userFundsPO.getBonus()))<=0) {
            UserCashPO userCashPO = new UserCashPO();
            userCashPO.setId(ymlConfig.getPkId());
            userCashPO.setUser_id(userInfo.getId());
            userCashPO.setReal_name(userInfo.getReal_name());
            userCashPO.setMobile(userInfo.getMobile());
            userCashPO.setPay_way(5);
            userCashPO.setPay_account(orderId+"");
            userCashPO.setType(4);
            userCashPO.setStatus(4);
            //userCashPO.setRemainder(userFundsPO.getBalance());
            if(money.compareTo(userFundsPO.getBonus().setScale(2,BigDecimal.ROUND_DOWN))>0){
                money = money.subtract(userFundsPO.getBonus());
                userCashPO.setPay_amount(userFundsPO.getBonus());
                userFundsPO.setBonus(new BigDecimal(0));
            }else{
                userFundsPO.setBonus(userFundsPO.getBonus().subtract(money));
                userCashPO.setPay_amount(money);
                money = new BigDecimal(0);
            }
            userCashPO.setRemainder(userFundsPO.getBonus());
            userCashMapper.insert(userCashPO);
            this.baseMapper.updateUserBonus(userInfo.getId(), userFundsPO.getBonus());
        }
        return money;
    }


    @Transactional
    @Override
    public boolean saveBalanceConsume(UserInfoPO userInfoPO, BigDecimal money, Long orderId,Long couponId) throws Exception {
        Long userId = userInfoPO.getId();
        //修改订单状态
        boolean canPay = true;
        UserCouponPO userCouponPO = new UserCouponPO();
        UserCouponPO coup = null;
        if(couponId!=null) {
            userCouponPO.setCoupon_id(couponId);
            userCouponPO.setUser_id(userId);
            coup = userCouponMapper.selectOne(userCouponPO);
        }
        SysCouponPO sysCouponPO = sysCouponMapper.selectById(couponId);
        //校验优惠券
        if(coup !=null && coup.getStatus()!=0 && coup.getEnd_time().before(new Date())){
            canPay = false;
        }
        //校验支付金额是否相等
        if(canPay){
            UserOrderPO order = userOrderService.selectById(orderId);
            if(order.getPay_amount().compareTo(BigDecimal.ZERO) <= 0 ){
                canPay = false;
            }
            BigDecimal pay = money;
            if(sysCouponPO!=null){
                pay = pay.add(sysCouponPO.getMoney());
            }
            if(order.getPay_amount().compareTo(pay)>0) {
                canPay = false;
            }
        }
        //校验余额是否够
        if(canPay){
            UserFundsPO userFundsPO = userFundsMapper.selectById(userId);
            BigDecimal userBalance = userFundsPO.getBalance();
            BigDecimal userBonus = userFundsPO.getBonus();
            BigDecimal totals = userBalance.add(userBonus);
            if(totals.compareTo(money)<0)
                canPay = false;
        }
        if(canPay) {
            //去支付
            if (null != userInfoPO) {
                //当支付金额为0时，生成一条0余额支付的记录
                if (money.compareTo(BigDecimal.ZERO) == 0) {
                    this.saveRechargeOrConsume(userId, BigDecimal.ZERO, 4, 4, null, null);
                }
                BigDecimal _money = saveBonuseConsume(userInfoPO, money, orderId);
                boolean result;
                if (0 == _money.intValue()) {
                    result = true;
                } else {
                    result = this.saveRechargeOrConsume(userId, _money, 4, 4, null, null);
                }
                if (result) {
                    //修改订单状态  余额购买
                    boolean flag = updateOrderStatus(userId, orderId, 4, 2);
                    if (!flag) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动开启事务回滚
                        return false;
                    }
                } else {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动开启事务回滚
                    return false;
                }
            }
        }else
            return false;
        return true;
    }

    @Transactional
    @Override
    public boolean saveAlipayConsume(UserInfoPO userInfoPO, BigDecimal money, Long orderId, String alipayAccount,Long couponId,BigDecimal balance) throws Exception {
        //修改订单状态
        boolean canPay = true;
        Long userId = userInfoPO.getId();
        UserCouponPO coup = null;
        UserOrderPO order = userOrderService.selectById(orderId);
        if(couponId!=null) {
            Wrapper wrapper = new EntityWrapper();
            wrapper.eq("user_id",userId);
            wrapper.eq("coupon_id",couponId);
            List<UserCouponPO> userCouponPOList = userCouponMapper.selectList(wrapper);
            if(userCouponPOList!=null && userCouponPOList.size()!=0){
                coup = userCouponPOList.get(0);
            }
        }
        SysCouponPO sysCouponPO = sysCouponMapper.selectById(couponId);
        //校验优惠券
        if(coup !=null && coup.getStatus()!=0 && coup.getEnd_time().before(new Date())){
            canPay = false;
        }
        //校验支付金额是否相等
        if(canPay){
            if(order.getPay_amount().compareTo(BigDecimal.ZERO) <= 0 ){
                canPay = false;
            }
            BigDecimal pay = money.add(balance);
            if(sysCouponPO!=null){
                pay = pay.add(sysCouponPO.getMoney());
            }
            if(order.getPay_amount().compareTo(pay)!=0) {
                canPay = false;
            }
        }
        //校验余额是否够
        if(canPay && balance.compareTo(BigDecimal.ZERO) != 0){
            UserFundsPO userFundsPO = userFundsMapper.selectById(userId);
            BigDecimal userBalance = userFundsPO.getBalance();
            BigDecimal userBonus = userFundsPO.getBonus();
            BigDecimal totals = userBalance.add(userBonus);
            if(totals.compareTo(balance)<0)
                canPay = false;
        }
        //退款
        if(canPay) {
            boolean flag = updateOrderStatus(userId, orderId,1,2);
            //支付成功，如果有余额抵扣，进行余额扣款
            if(flag){
                UserCashPO userCashPO = new UserCashPO();
                userCashPO.setId(orderId);
                userCashPO.setUser_id(userId);
                userCashPO.setReal_name(userInfoPO.getReal_name());
                userCashPO.setMobile(userInfoPO.getMobile());
                userCashPO.setPay_way(1);
                userCashPO.setPay_account(alipayAccount);
                userCashPO.setPay_amount(money);
                userCashPO.setType(4);
                userCashPO.setOrder_id(orderId);
                userCashPO.setOrder_money(order.getPay_amount());
                Integer status = 4;
                userCashPO.setStatus(status);
                //支付成功，如果有优惠券抵扣，修改优惠券状态为已使用
                if(!ObjectUtils.isEmpty(couponId)){
                    //支付成功后修改优惠券为已使用
                    sysActivityService.updateCouponUsed(userId,couponId);
                    userCashPO.setCoupon_id(couponId);
                    userCashPO.setCoupon_money(sysCouponPO.getMoney());
                }
                userCashMapper.insert(userCashPO);
                if(null != userInfoPO && balance.compareTo(BigDecimal.ZERO)==1) {
                    //当支付金额为0时，生成一条0余额支付的记录
                    BigDecimal _money = saveBonuseConsume(userInfoPO,balance,orderId);
                    if(_money.compareTo(BigDecimal.ZERO)==0) {
                    }else {
                        this.saveRechargeOrConsume(userId, _money, 4, 4, null, null);
                    }
                }
            }else {
                //取消订单，发起退款
                userOrderService.backMoneyToBalance(String.valueOf(userId), money);
            }
        }else {
            //取消订单，发起退款
            userOrderService.backMoneyToBalance(String.valueOf(orderId), money);
        }
        return true;
    }

    @Transactional
    @Override
    public boolean saveWechatConsume(UserInfoPO userInfoPO, BigDecimal money, Long orderId, String wechatAccount,Long couponId,BigDecimal balance) throws Exception {
        //修改订单状态
        boolean canPay = true;
        Long userId = userInfoPO.getId();
        UserCouponPO coup = null;
        UserOrderPO order = userOrderService.selectById(orderId);
        if(couponId!=null) {
            Wrapper wrapper = new EntityWrapper();
            wrapper.eq("user_id",userId);
            wrapper.eq("coupon_id",couponId);
            List<UserCouponPO> userCouponPOList = userCouponMapper.selectList(wrapper);
            if(userCouponPOList!=null && userCouponPOList.size()!=0){
                coup = userCouponPOList.get(0);
            }
        }
        SysCouponPO sysCouponPO = sysCouponMapper.selectById(couponId);
        //校验优惠券
        if(coup !=null && coup.getStatus()!=0 && coup.getEnd_time().before(new Date())){
            canPay = false;
        }
        //校验支付金额是否相等
        if(canPay){
            if(order.getPay_amount().compareTo(BigDecimal.ZERO) <= 0 ){
                canPay = false;
            }
            BigDecimal pay = money.add(balance);
            if(sysCouponPO!=null){
                pay = pay.add(sysCouponPO.getMoney());
            }
            if(order.getPay_amount().compareTo(pay)!=0) {
                canPay = false;
            }
        }
        //校验余额是否够
        if(canPay && balance.compareTo(BigDecimal.ZERO) != 0){
            UserFundsPO userFundsPO = userFundsMapper.selectById(userId);
            BigDecimal userBalance = userFundsPO.getBalance();
            BigDecimal userBonus = userFundsPO.getBonus();
            BigDecimal totals = userBalance.add(userBonus);
            if(totals.compareTo(balance)<0)
                canPay = false;
        }
        //退款
        if(canPay) {
            boolean flag = updateOrderStatus(userId, orderId,1,2);
            //支付成功，如果有余额抵扣，进行余额扣款
            if(flag){
                UserCashPO userCashPO = new UserCashPO();
                userCashPO.setId(orderId);
                userCashPO.setUser_id(userId);
                userCashPO.setReal_name(userInfoPO.getReal_name());
                userCashPO.setMobile(userInfoPO.getMobile());
                userCashPO.setPay_way(6);
                userCashPO.setPay_account(wechatAccount);
                userCashPO.setPay_amount(money);
                userCashPO.setType(4);
                userCashPO.setOrder_id(orderId);
                userCashPO.setOrder_money(order.getPay_amount());
                Integer status = 4;
                userCashPO.setStatus(status);
                //支付成功，如果有优惠券抵扣，修改优惠券状态为已使用
                if(!ObjectUtils.isEmpty(couponId)){
                    //支付成功后修改优惠券为已使用
                    sysActivityService.updateCouponUsed(userId,couponId);
                    userCashPO.setCoupon_id(couponId);
                    userCashPO.setCoupon_money(sysCouponPO.getMoney());
                }
                userCashMapper.insert(userCashPO);
                if(null != userInfoPO && balance.compareTo(BigDecimal.ZERO)==1) {
                    //当支付金额为0时，生成一条0余额支付的记录
                    BigDecimal _money = saveBonuseConsume(userInfoPO,balance,orderId);
                    if(_money.compareTo(BigDecimal.ZERO)==0) {
                    }else {
                        this.saveRechargeOrConsume(userId, _money, 4, 6, null, null);
                    }
                }
            }else {
                //取消订单，发起退款
                userOrderService.backMoneyToBalance(String.valueOf(userId), money);
            }
        }else {
            //取消订单，发起退款
            userOrderService.backMoneyToBalance(String.valueOf(orderId), money);
        }
        return true;
    }

    public boolean updateOrderStatus(Long userId, Long orderId, Integer payWay, Integer status){
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        UserOrderPO orderPO = new UserOrderPO();
        orderPO.setId(orderId);
        orderPO.setPay_way(payWay);
        orderPO.setStatus(status);
        if(2==status)
            orderPO.setTicket_status(1);
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("user_id",userId);
        wrapper.in("status","2,3,4,5,6,10");
        Integer count = userOrderMapper.selectCount(wrapper);

        Wrapper wrapper1 = new EntityWrapper();
        wrapper1.eq("order_id", userId);
        wrapper1.eq("type",7);
        wrapper1.eq("info","邀请用户首次下单奖励");
        Integer count1 = userCashMapper.selectCount(wrapper1);

        wrapper = new EntityWrapper();
        wrapper.eq("id", orderId);
        wrapper.in("status", "0,7");
        Integer flag = userOrderMapper.update(orderPO, wrapper);

        if(flag<1){
            return false;
        }
        UserOrderPO userOrderPO = userOrderMapper.selectById(orderId);
        //被邀请首次下单成功(充值成功) 保存用户邀请记录表
        try {
            if (count == 0) {
                //用户首次参与竞猜奖励
                Wrapper firstOrderWrapper = new EntityWrapper();
                firstOrderWrapper.eq("user_id", userId);
                firstOrderWrapper.eq("type", "7");
                firstOrderWrapper.eq("info", "用户首次参与竞猜奖励");
                Integer firstOrderCount = userCashMapper.selectCount(firstOrderWrapper);
                if(firstOrderCount==0){
                    SysActivityBO sysActivityBO = new SysActivityBO();
                    sysActivityBO.setActivityId(ActivityIdEnum.FIRST_ORDER_REWARD.getId());
                    sysActivityBO.setUserId(userId);
//                    sysActivityService.saveUserActivity(sysActivityBO);
                }
                if (status == 2 && count1==0) {
                    //根据userid查询invitorid
                    UserInviteRecordPO inviteRecordPO = new UserInviteRecordPO();
                    inviteRecordPO.setUser_id(userId);
                    UserInviteRecordPO invitePO = userInviteMapper.selectOne(inviteRecordPO);
                    if (invitePO != null){
//                        UserAgentPO userAgentPO = new UserAgentPO();
//                        userAgentPO.setUser_id(invitePO.getInviter_id());
//                        UserAgentPO agentPO = userAgentMapper.selectOne(userAgentPO);
//                        if(agentPO==null || (agentPO!=null && agentPO.getStatus()!=0)){
                            //邀请人需为累积充值满100用户,且每日最多奖励40
//                            Wrapper inviterWrapper = new EntityWrapper();
//                            inviterWrapper.eq("user_id", invitePO.getInviter_id());
//                            inviterWrapper.in("type", "1");
//                            Wrapper inviterCountWrapper = new EntityWrapper();
//                            inviterCountWrapper.eq("user_id", invitePO.getInviter_id());
//                            inviterCountWrapper.like("create_time",f.format(new Date()));
//                            inviterCountWrapper.eq("type", "7");
//                            inviterCountWrapper.eq("info", "邀请用户首次下单奖励");
//                            Integer inviterCashCount = userCashMapper.selectCount(inviterCountWrapper);
//                            SysConfigPO sysConfigPO = sysConfigMapper.getByKey("INVITATION_AWARDS");
//                            Integer inviteAwardCount = Integer.valueOf(sysConfigPO.getCval());
//                            if(inviterCashCount<inviteAwardCount){
                                userInviteMapper.updateByInInvitorId(userId, orderId);
                                SysActivityBO sysActivityBO = new SysActivityBO();
                                sysActivityBO.setUserId(userId);
                                sysActivityBO.setInviterId(String.valueOf(invitePO.getInviter_id()));
                                sysActivityBO.setOrderId(orderId);
                                sysActivityBO.setActivityId(ActivityIdEnum.INVITE_ORDER.getId());
                                sysActivityBO.setConditionMoney(userOrderPO.getPay_amount());
                                sysActivityService.saveUserActivity(sysActivityBO);
//                            }
//                        }
                    }
                }
            }
        } catch (Exception e){
            log.info("userInviteMapper.updateByInInvitorId",e);
        }

        return true;
    }
    @Transactional
    @Override
    public boolean saveWinning(Long userId, BigDecimal money, Long orderId) throws Exception {
        boolean result = this.saveRechargeOrConsume(userId, money, 3, 3, null, null);
        if (result) {
            //修改订单状态
            UserOrderPO orderPO = new UserOrderPO();
            orderPO.setId(orderId);
            orderPO.setPrize(money);
            orderPO.setStatus(6);
            Wrapper wrapper = new EntityWrapper();
            wrapper.eq("id", orderId);
            wrapper.eq("status", 5);
            Integer i = userOrderMapper.update(orderPO, wrapper);
            if (i < 1) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动开启事务回滚
                return false;
            }
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动开启事务回滚
            return false;
        }
        return true;
    }

    @Override
    public boolean saveDrawCashSuccess(Long cashId) {
        //成功
        UserCashPO cashPO = new UserCashPO();
        cashPO.setId(cashId);
        cashPO.setStatus(4);

        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("id", cashId);
        wrapper.eq("status", 1);
        return userCashMapper.update(cashPO, wrapper) > 0;
    }

    /**
     * Isolation.REPEATABLE_READ  事物级别：幻读脏读
     *
     * @param userId
     * @param cashId
     * @param failNotes
     * @param money
     * @return
     */
    @Transactional(isolation = Isolation.REPEATABLE_READ)
    @Override
    public boolean saveDrawCashFail(Long userId, Long cashId, String failNotes, BigDecimal money) {
        UserCashPO cashPO = new UserCashPO();
        cashPO.setId(cashId);
        cashPO.setStatus(3);
        cashPO.setInfo(failNotes);
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("id", cashId);
        wrapper.eq("status", 4);
        boolean flag = userCashMapper.update(cashPO, wrapper) > 0;
        if (flag) {
            UserFundsPO fundsPO = this.baseMapper.selectById(userId);
            fundsPO.setUser_id(userId);
            BigDecimal remainder = fundsPO.getBalance().add(money).setScale(2, 4);
            fundsPO.setBalance(remainder);
            flag = this.baseMapper.updateById(fundsPO) > 0;
            if (!flag) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动开启事务回滚
            }
        }
        return flag;
    }

    @Override
    public Map<String, Object> queryUserFundsByUId(Long userId) {
        return baseMapper.queryUserFundsByUId(userId);
    }

    @Override
    public Result
    payOrder(UserOrderVO vo,Long couponId) {
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        Result result = new Result();
        String key = "PAY_ORDER_"+vo.getId();
        String value = stringRedisTemplate.opsForValue().get(key);
        UserOrderPO order = userOrderMapper.selectById(vo.getId());
        if(order.getStatus()==2){
            return new Result(CodeEnum.FAIL.getCode(), "您的订单已支付！");
        }
        if(StrUtils.isNotEmpty(value)){
            return new Result(CodeEnum.FAIL.getCode(), "您还有未处理的支付订单，请稍后操作！");
        }
        try{
            synchronized("") {
                stringRedisTemplate.opsForValue().set(key, key);
                Map<String, Object> userFundsMap = this.baseMapper.getById(Long.valueOf(vo.getUserId()));
                BigDecimal balance = (BigDecimal) userFundsMap.get("balance");  //中奖趣豆
                BigDecimal lotBean = (BigDecimal) userFundsMap.get("lotBean");  //签到领奖趣豆
                BigDecimal bonus = (BigDecimal) userFundsMap.get("bonus");  //充值趣豆
                BigDecimal subTotal = balance.add(lotBean).add(bonus);  //总余额
                BigDecimal payAmount = new BigDecimal(vo.getPayAmount());   //订单金额
                BigDecimal couponMoney = null;
                //优惠券校验
                if (couponId != null){
                    Map<String, Object> cMap = sysActivityService.saveCouponConsume(couponId, Long.valueOf(vo.getId()));
                    UserCouponPO userCouponPO = new UserCouponPO();
                    userCouponPO.setUser_id(Long.valueOf(vo.getUserId()));
                    userCouponPO.setCoupon_id(couponId);
                    userCouponPO = userCouponMapper.selectOne(userCouponPO);
                    SysCouponPO sysCouponPO = sysCouponMapper.selectById(couponId);
                    if (sysCouponPO == null || userCouponPO == null || userCouponPO.getEnd_time().before(new Date()) || userCouponPO.getStatus() != 0)
                        return new Result(CodeEnum.FAIL.getCode(), "优惠券不可用");
                    if (payAmount.compareTo(sysCouponPO.getCondition_money()) == -1)
                        return new Result(CodeEnum.FAIL.getCode(), "优惠券不可用");
                    payAmount = payAmount.subtract(sysCouponPO.getMoney());
                    couponMoney = sysCouponPO.getMoney();
                    if (payAmount.compareTo(BigDecimal.ZERO) == -1)
                        payAmount = BigDecimal.ZERO;
                    //修改优惠券状态为已使用
                    userCouponMapper.updateUserCouponStatus(Long.valueOf(vo.getUserId()),couponId,1);
                }

                if (subTotal.compareTo(payAmount) == -1) {
                    return new Result(CodeEnum.FAIL.getCode(), "余额不足，请充值！");
                }
                Long userId = Long.valueOf(vo.getUserId());
                Long orderId = Long.valueOf(vo.getId());
                UserInfoPO userInfoPO = userInfoMapper.selectById(userId);
                if (userInfoPO == null)
                    return new Result(CodeEnum.FAIL.getCode(), "此用户不存在");
                BigDecimal money = lotBeanConsume(userInfoPO, payAmount, orderId);    //平台赠送趣豆消费
                if (money.compareTo(BigDecimal.ZERO) == 1) {
                    BigDecimal _money = bonusConsume(userInfoPO, money, orderId);    //充值趣豆消费
                    if (_money.compareTo(BigDecimal.ZERO) == 1) {
                        balanceConsume(userInfoPO, _money, orderId); //中奖趣豆消费
                    }
                }
                UserCashPO userCashPO = new UserCashPO();
                userCashPO.setId(ymlConfig.getPkId());
                userCashPO.setUser_id(userInfoPO.getId());
                userCashPO.setReal_name(userInfoPO.getReal_name());
                userCashPO.setMobile(userInfoPO.getMobile());
                userCashPO.setPay_way(3);
                userCashPO.setPay_account(orderId + "");
                userCashPO.setType(4);
                userCashPO.setStatus(4);
                userCashPO.setPay_amount(payAmount);
                userCashPO.setRemainder(subTotal.subtract(payAmount));
                userCashPO.setCoupon_id(couponId);
                userCashPO.setCoupon_money(couponMoney);
                userCashMapper.insert(userCashPO);
                //修改订单状态  余额购买
                updateOrderStatus(userId, orderId, 4, 2);
                //每日下单后再送166趣豆,直到送满18800趣豆为止
                /*Integer count = userOrderMapper.getTodayOrderCount(userId);
                if(count==1){
                    everydayFirstAward(userId);
                }*/
                //今日参与竞猜
                /*Wrapper todayOrderWrapper = new EntityWrapper();
                todayOrderWrapper.eq("user_id", userId);
                todayOrderWrapper.like("create_time",f.format(new Date()));
                todayOrderWrapper.eq("type", "7");
                todayOrderWrapper.eq("info", "用户今日参与竞猜奖励");
                Integer todayOrderCount = userCashMapper.selectCount(todayOrderWrapper);
                if(todayOrderCount==0){
                    SysActivityBO sysActivityBO = new SysActivityBO();
                    sysActivityBO.setActivityId(ActivityIdEnum.FIRST_TODAY_ORDER_REWARD.getId());
                    sysActivityBO.setUserId(userId);
                    sysActivityService.saveUserActivity(sysActivityBO);
                }
                //今日参与5次竞猜
                Wrapper userOrderWrapper = new EntityWrapper();
                userOrderWrapper.eq("user_id", userId);
                userOrderWrapper.like("create_time",f.format(new Date()));
                userOrderWrapper.eq("ticket_status",1);
                Integer userOrderCount = userOrderMapper.selectCount(userOrderWrapper);
                if(userOrderCount>=5){
                    Wrapper todayOrder5Wrapper = new EntityWrapper();
                    todayOrder5Wrapper.eq("user_id", userId);
                    todayOrder5Wrapper.like("create_time",f.format(new Date()));
                    todayOrder5Wrapper.eq("type", "7");
                    todayOrder5Wrapper.eq("info", "用户今日参与5次竞猜奖励");
                    Integer todayOrder5Count = userCashMapper.selectCount(todayOrder5Wrapper);
                    if(todayOrder5Count==0){
                        SysActivityBO sysActivityBO = new SysActivityBO();
                        sysActivityBO.setActivityId(ActivityIdEnum.FIRST_TODAY_ORDER_5_REWARD.getId());
                        sysActivityBO.setUserId(userId);
                        sysActivityService.saveUserActivity(sysActivityBO);
                    }
                }
                //今日下单竞猜足球
                if("21".equals(vo.getLotteryId())){
                    Wrapper todayOrderFootballWrapper = new EntityWrapper();
                    todayOrderFootballWrapper.eq("user_id", userId);
                    todayOrderFootballWrapper.like("create_time",f.format(new Date()));
                    todayOrderFootballWrapper.eq("type", "7");
                    todayOrderFootballWrapper.eq("info", "用户今日下单竞猜足球奖励");
                    Integer todayOrderFootballCount = userCashMapper.selectCount(todayOrderFootballWrapper);
                    if(todayOrderFootballCount==0){
                        SysActivityBO sysActivityBO = new SysActivityBO();
                        sysActivityBO.setActivityId(ActivityIdEnum.FIRST_TODAY_ORDER_FOOTBALL_REWARD.getId());
                        sysActivityBO.setUserId(userId);
                        sysActivityService.saveUserActivity(sysActivityBO);
                    }
                }
                //今日下单欢乐猜球
                if("10".equals(vo.getLotteryId())){
                    Wrapper eSportsWrapper = new EntityWrapper();
                    eSportsWrapper.eq("matchId",vo.getPeriod());
                    ESportsPO eSportsPO = new ESportsPO();
                    eSportsPO.setMatch_id(Long.valueOf(vo.getPeriod()));
                    eSportsPO = eSportsMapper.selectOne(eSportsPO);
                    if(eSportsPO != null) {
                        if (eSportsPO.getType() == 5 || eSportsPO.getType() == 6) {
                            Wrapper todayOrderGuessballWrapper = new EntityWrapper();
                            todayOrderGuessballWrapper.eq("user_id", userId);
                            todayOrderGuessballWrapper.like("create_time", f.format(new Date()));
                            todayOrderGuessballWrapper.eq("type", "7");
                            todayOrderGuessballWrapper.eq("info", "用户今日下单欢乐猜球奖励");
                            Integer todayOrderGuessballCount = userCashMapper.selectCount(todayOrderGuessballWrapper);
                            if (todayOrderGuessballCount == 0) {
                                SysActivityBO sysActivityBO = new SysActivityBO();
                                sysActivityBO.setActivityId(ActivityIdEnum.FIRST_TODAY_ORDER_GUESSBALL_REWARD.getId());
                                sysActivityBO.setUserId(userId);
                                sysActivityService.saveUserActivity(sysActivityBO);
                            }
                        } else {
                            Wrapper todayOrderElectricWrapper = new EntityWrapper();
                            todayOrderElectricWrapper.eq("user_id", userId);
                            todayOrderElectricWrapper.like("create_time", f.format(new Date()));
                            todayOrderElectricWrapper.eq("type", "7");
                            todayOrderElectricWrapper.eq("info", "用户今日下单电竞竞猜奖励");
                            Integer todayOrderElectricCount = userCashMapper.selectCount(todayOrderElectricWrapper);
                            if (todayOrderElectricCount == 0) {
                                SysActivityBO sysActivityBO = new SysActivityBO();
                                sysActivityBO.setActivityId(ActivityIdEnum.FIRST_TODAY_ORDER_ELECTRIC_REWARD.getId());
                                sysActivityBO.setUserId(userId);
                                sysActivityService.saveUserActivity(sysActivityBO);
                            }
                        }
                    }
                }
                //今日下单满20元
                List<UserOrderPO> userOrderPOList = userOrderMapper.selectList(userOrderWrapper);
                BigDecimal todayTotalMoney = BigDecimal.ZERO;
                for(UserOrderPO userOrderPO : userOrderPOList){
                    todayTotalMoney = todayTotalMoney.add(userOrderPO.getPay_amount());
                }
                if(todayTotalMoney.compareTo(new BigDecimal("2000"))>=0){
                    Wrapper todayOrder20RMBWrapper = new EntityWrapper();
                    todayOrder20RMBWrapper.eq("user_id", userId);
                    todayOrder20RMBWrapper.like("create_time", f.format(new Date()));
                    todayOrder20RMBWrapper.eq("type", "7");
                    todayOrder20RMBWrapper.eq("info", "用户今日下单满20元奖励");
                    Integer todayOrder20RMBCount = userCashMapper.selectCount(todayOrder20RMBWrapper);
                    if (todayOrder20RMBCount == 0) {
                        SysActivityBO sysActivityBO = new SysActivityBO();
                        sysActivityBO.setActivityId(ActivityIdEnum.FIRST_TODAY_ORDER_20RMB_REWARD.getId());
                        sysActivityBO.setUserId(userId);
                        sysActivityService.saveUserActivity(sysActivityBO);
                    }
                }
                //今日下单满50元
                if(todayTotalMoney.compareTo(new BigDecimal("5000"))>=0){
                    Wrapper todayOrder50RMBWrapper = new EntityWrapper();
                    todayOrder50RMBWrapper.eq("user_id", userId);
                    todayOrder50RMBWrapper.like("create_time", f.format(new Date()));
                    todayOrder50RMBWrapper.eq("type", "7");
                    todayOrder50RMBWrapper.eq("info", "用户今日下单满50元奖励");
                    Integer todayOrder50RMBCount = userCashMapper.selectCount(todayOrder50RMBWrapper);
                    if (todayOrder50RMBCount == 0) {
                        SysActivityBO sysActivityBO = new SysActivityBO();
                        sysActivityBO.setActivityId(ActivityIdEnum.FIRST_TODAY_ORDER_50RMB_REWARD.getId());
                        sysActivityBO.setUserId(userId);
                        sysActivityService.saveUserActivity(sysActivityBO);
                    }
                }
                //今日下单满100元
                if(todayTotalMoney.compareTo(new BigDecimal("10000"))>=0){
                    Wrapper todayOrder100RMBWrapper = new EntityWrapper();
                    todayOrder100RMBWrapper.eq("user_id", userId);
                    todayOrder100RMBWrapper.like("create_time", f.format(new Date()));
                    todayOrder100RMBWrapper.eq("type", "7");
                    todayOrder100RMBWrapper.eq("info", "用户今日下单满100元奖励");
                    Integer todayOrder100RMBCount = userCashMapper.selectCount(todayOrder100RMBWrapper);
                    if (todayOrder100RMBCount == 0) {
                        SysActivityBO sysActivityBO = new SysActivityBO();
                        sysActivityBO.setActivityId(ActivityIdEnum.FIRST_TODAY_ORDER_100RMB_REWARD.getId());
                        sysActivityBO.setUserId(userId);
                        sysActivityService.saveUserActivity(sysActivityBO);
                    }
                }*/
                result.setData(vo);
            }
        }catch(Exception e){
            log.error(vo.getId()+"支付失败",e);
        }finally {
            stringRedisTemplate.delete(key);
        }
        return result;
    }
    public void everydayFirstAward(Long userId){
        SysCouponPO sysCouponPO = new SysCouponPO();
        sysCouponPO.setActivity_id(6L);
        sysCouponPO.setStatus(1);
        sysCouponPO = sysCouponMapper.selectOne(sysCouponPO);
        if(sysCouponPO!=null) {
            BigDecimal money = sysCouponPO.getMoney();
            UserFundsPO userFundsPO = userFundsMapper.selectById(userId);
            BigDecimal grants = userFundsPO.getGrants();
            if(grants.compareTo(BigDecimal.ZERO)==1){
                if(grants.compareTo(money)==-1){
                    money = grants;
                }
                UserInfoPO userInfoPO = userInfoMapper.selectById(userId);
                UserCashPO userCashPO = new UserCashPO();
                userCashPO.setId(ymlConfig.getPkId());
                userCashPO.setUser_id(userInfoPO.getId());
                userCashPO.setReal_name(userInfoPO.getReal_name());
                userCashPO.setMobile(userInfoPO.getMobile());
                userCashPO.setPay_way(7);
                userCashPO.setPay_account("ZQXQ");
                userCashPO.setType(7);
                userCashPO.setStatus(4);
                userCashPO.setPay_amount(money);
                userCashPO.setInfo("每日下单赠送趣豆");
                userCashService.insert(userCashPO);
                BigDecimal lotBean = userFundsPO.getLot_bean();
                userFundsPO.setLot_bean(lotBean.add(money));
                userFundsPO.setGrants(grants.subtract(money));
                userFundsMapper.updateById(userFundsPO);
                userWindowMsgService.saveUserMsg(userInfoPO.getId(),"下单成功",String.valueOf(money.intValue()),4);
            }
        }
    }

    @Override
    public Result exchangeDiamonds(Long userId, BigDecimal payAmount) {
        Result result = new Result();
        String key = "EXCHANGE_DIAMOND_RATIO_"+userId;
        String value = stringRedisTemplate.opsForValue().get(key);
        if(StrUtils.isNotEmpty(value)){
            return new Result(CodeEnum.FAIL.getCode(), "你还有未处理的换钻，请稍后操作！");
        }
        try{
            stringRedisTemplate.opsForValue().set(key,key);
            UserFundsPO userFundsPO = userFundsMapper.selectById(userId);
            BigDecimal balance = userFundsPO.getBalance();  //中奖趣豆
            BigDecimal lotBean = userFundsPO.getLot_bean();    //奖励趣豆
            BigDecimal bonus = userFundsPO.getBonus();      //充值趣豆
            if(payAmount.compareTo(new BigDecimal(0))==-1){
                return new Result(CodeEnum.FAIL.getCode(),"输入趣豆不能小于0！");
            }
            if((balance.add(bonus)).compareTo(payAmount)==-1){
                return new Result(CodeEnum.FAIL.getCode(),"余额不足！");
            }
            SysConfigPO sysConfigPO = sysConfigMapper.getByKey("EXCHANGE_DIAMOND_RATIO");
            BigDecimal exchangeDiamondRatio = new BigDecimal(sysConfigPO.getCval());
            BigDecimal diamonds = userFundsPO.getDiamonds();
            BigDecimal addDiamonds = payAmount.divide(exchangeDiamondRatio,2,BigDecimal.ROUND_HALF_UP);
            BigDecimal bonusAmount = balance.subtract(payAmount);
            UserInfoPO userInfo = userInfoMapper.selectById(userId);
            if(bonusAmount.compareTo(BigDecimal.ZERO)==-1) {
                userFundsPO.setBalance(BigDecimal.ZERO);
            }else{
                userFundsPO.setBalance(bonusAmount);
            }
            UserCashPO userCashPO = new UserCashPO();
            userCashPO.setId(ymlConfig.getPkId());
            userCashPO.setUser_id(userInfo.getId());
            userCashPO.setReal_name(userInfo.getReal_name());
            userCashPO.setMobile(userInfo.getMobile());
            userCashPO.setPay_way(4);
            userCashPO.setPay_account(null);
            userCashPO.setType(8);
            userCashPO.setStatus(4);
            userCashPO.setPay_amount(payAmount);
            userCashPO.setRemainder(userFundsPO.getBalance());
            userCashMapper.insert(userCashPO);
            if(bonusAmount.compareTo(BigDecimal.ZERO)==-1){
                userFundsPO.setBonus(bonus.add(bonusAmount));
            }
            userFundsPO.setDiamonds(diamonds.add(addDiamonds));
            UserCashPO userCashPO2 = new UserCashPO();
            userCashPO2.setId(ymlConfig.getPkId());
            userCashPO2.setUser_id(userInfo.getId());
            userCashPO2.setReal_name(userInfo.getReal_name());
            userCashPO2.setMobile(userInfo.getMobile());
            userCashPO2.setPay_way(8);
            userCashPO2.setPay_account(null);
            userCashPO2.setType(11);
            userCashPO2.setStatus(4);
            userCashPO2.setPay_amount(addDiamonds);
            userCashPO2.setRemainder(userFundsPO.getDiamonds());
            userCashMapper.insert(userCashPO2);
            //抽钻后的损失的趣豆奖励到用户余额
            BigDecimal money = payAmount.subtract(addDiamonds);
            if(money.compareTo(BigDecimal.ZERO)!=0){
                userFundsPO.setLot_bean(lotBean.add(money));
                UserCashPO userCashPO3 = new UserCashPO();
                userCashPO3.setId(ymlConfig.getPkId());
                userCashPO3.setUser_id(userInfo.getId());
                userCashPO3.setReal_name(userInfo.getReal_name());
                userCashPO3.setMobile(userInfo.getMobile());
                userCashPO3.setPay_way(7);
                userCashPO3.setPay_account("ZQXQ");
                userCashPO3.setType(7);
                userCashPO3.setStatus(4);
                userCashPO3.setPay_amount(money);
                userCashPO3.setRemainder(userFundsPO.getLot_bean());
                userCashPO3.setInfo("抽钻奖励趣豆");
                userCashMapper.insert(userCashPO3);
            }
            this.baseMapper.updateById(userFundsPO);
            Map<String,Object> map = new HashMap();
            map.put("exchangeDiamonds",addDiamonds);
            map.put("lossReward",money);
            result.setData(map);
        }catch(Exception e){
            log.error(userId+"提现失败",e);
        }finally {
            stringRedisTemplate.delete(key);
        }

        return result;
    }

    /**
     * 平台赠送趣豆消费
     */
    private BigDecimal lotBeanConsume(UserInfoPO userInfo, BigDecimal money, Long orderId){
        UserFundsPO userFundsPO = userFundsMapper.selectById(userInfo.getId());
        if (null != userFundsPO && userFundsPO.getLot_bean().intValue()>0){
//            UserCashPO userCashPO = new UserCashPO();
//            userCashPO.setId(ymlConfig.getPkId());
//            userCashPO.setUser_id(userInfo.getId());
//            userCashPO.setReal_name(userInfo.getReal_name());
//            userCashPO.setMobile(userInfo.getMobile());
//            userCashPO.setPay_way(7);
//            userCashPO.setPay_account(orderId+"");
//            userCashPO.setType(4);
//            userCashPO.setStatus(4);
            if(money.compareTo(userFundsPO.getLot_bean().setScale(2,BigDecimal.ROUND_DOWN))>0){
                money = money.subtract(userFundsPO.getLot_bean());
//                userCashPO.setPay_amount(userFundsPO.getLot_bean());
                userFundsPO.setLot_bean(new BigDecimal(0));
            }else{
                userFundsPO.setLot_bean(userFundsPO.getLot_bean().subtract(money));
//                userCashPO.setPay_amount(money);
                money = new BigDecimal(0);
            }
//            userCashPO.setRemainder(userFundsPO.getLot_bean());
//            userCashMapper.insert(userCashPO);
            userFundsPO.setConsume_status(1);
            this.baseMapper.updateById(userFundsPO);
        }
        return money;
    }
    /**
     * 充值趣豆消费
     */
    private BigDecimal bonusConsume(UserInfoPO userInfo, BigDecimal money, Long orderId){
        UserFundsPO userFundsPO = userFundsMapper.selectById(userInfo.getId());
        if (null != userFundsPO && userFundsPO.getBonus().intValue()>0){
//            UserCashPO userCashPO = new UserCashPO();
//            userCashPO.setId(ymlConfig.getPkId());
//            userCashPO.setUser_id(userInfo.getId());
//            userCashPO.setReal_name(userInfo.getReal_name());
//            userCashPO.setMobile(userInfo.getMobile());
//            userCashPO.setPay_way(5);
//            userCashPO.setPay_account(orderId+"");
//            userCashPO.setType(4);
//            userCashPO.setStatus(4);
            if(money.compareTo(userFundsPO.getBonus().setScale(2,BigDecimal.ROUND_DOWN))>0){
                money = money.subtract(userFundsPO.getBonus());
//                userCashPO.setPay_amount(userFundsPO.getBonus());
                userFundsPO.setBonus(new BigDecimal(0));
            }else{
                userFundsPO.setBonus(userFundsPO.getBonus().subtract(money));
//                userCashPO.setPay_amount(money);
                money = new BigDecimal(0);
            }
//            userCashPO.setRemainder(userFundsPO.getBonus());
//            userCashMapper.insert(userCashPO);
            userFundsPO.setConsume_status(1);
            this.baseMapper.updateById(userFundsPO);
        }
        return money;
    }

    /**
     * 中奖趣豆消费
     */
    private BigDecimal balanceConsume(UserInfoPO userInfo, BigDecimal money, Long orderId){
        UserFundsPO userFundsPO = userFundsMapper.selectById(userInfo.getId());
        if (null != userFundsPO && userFundsPO.getBalance().intValue()>0){
//            UserCashPO userCashPO = new UserCashPO();
//            userCashPO.setId(ymlConfig.getPkId());
//            userCashPO.setUser_id(userInfo.getId());
//            userCashPO.setReal_name(userInfo.getReal_name());
//            userCashPO.setMobile(userInfo.getMobile());
//            userCashPO.setPay_way(4);
//            userCashPO.setPay_account(orderId+"");
//            userCashPO.setType(4);
//            userCashPO.setStatus(4);
            if(money.compareTo(userFundsPO.getBalance().setScale(2,BigDecimal.ROUND_DOWN))>0){
                money = money.subtract(userFundsPO.getBalance());
//                userCashPO.setPay_amount(userFundsPO.getBalance());
                userFundsPO.setBalance(new BigDecimal(0));
            }else{
                userFundsPO.setBalance(userFundsPO.getBalance().subtract(money));
//                userCashPO.setPay_amount(money);
                money = new BigDecimal(0);
            }
//            userCashPO.setRemainder(userFundsPO.getBalance());
//            userCashMapper.insert(userCashPO);
            userFundsPO.setConsume_status(1);
            this.baseMapper.updateById(userFundsPO);
        }
        return money;
    }
}
